/*
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-02-10 16:11:53
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-02-14 11:21:12
 * @Description:
 */
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { message } from 'ant-design-vue';
class Request {
  private instance: AxiosInstance;
  constructor(options: AxiosRequestConfig) {
    this.instance = axios.create(options);
    // options.headers;

    // 返回结果处理
    this.instance.interceptors.response.use(
      (res) => {
        if (res.data.success) {
          return res.data.data;
        } else if (res.data.errorCode == 'A0200') {

        }
        message.error(res.data.message || '请求失败');
        throw res.data;
      },
      (err) => {
        return err;
      }
    );
  }

  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, AxiosResponse>(config)
        .then((res) => {
          resolve(res as unknown as Promise<T>);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'GET' });
  }

  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST' });
  }

  put<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'PUT' });
  }

  delete<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'DELETE' });
  }
}

export default Request;
